package Concurrency4_GeekTime.Chapter01_BackGround;

import java.util.concurrent.TimeUnit;

/**
 * 功能说明：check the visibility issue
 * 1: commment volatile, run the main method
 * 2: uncomment volatile key word, check wether t1 thread stop immediately when t2 changed the flag
 * 开发人员：@author MaLi
 */
public class Base01_Visibility {
    //validity wether or not use "volatile", lead to different appearance
    private static /*volatile*/ boolean flag = true;
    public static void main(String[] args) {
        // thread1 : infinite loop
        Thread t1 = new Thread(() -> {
            while (flag) {
                // do nothing
            }
            System.out.println("thread1 stoped");
        }, "Thraed1");
        // thread2: change loop condition
        Thread t2 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                flag = false;
                System.out.println("flag has been changed");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        //check : wether loop stop immediately at the condition changed
        try {
            t1.start();
            t2.start();
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
